const express = require('express')
const router =express.Router()
const BannerSchema = require('../models/banner')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/Blog')
var fs = require('fs');


var file=require("formidable")
var path=require("path")

router.post("/update",(req,res)=>{
  const f=new file.IncomingForm()
  f.uploadDir="./img/banners"//上传目录 最好是使用express.static中间件同步
  f.keepExtensions = true
  f.parse(req,function(err,fields,files){  //其中fields表示你提交的表单数据对象，files表示你提交的文件对象
    console.log(fields)
    var fileName ='banner_'+fields.index+'.png';
    var targetFile = path.join("./img/banners", fileName);  
    //移动文件  
    fs.rename('./img/banners/invalid-name', targetFile, function (err) {  
        if (err) {  
            console.info(err);  
            res.json({code:400, data:{code:400, message:'操作失败'}});  
        } else {  
            //上传成功，返回文件的相对路径
            res.json({code:200, data:{code:200}});  
        }  
    }); 
  })
})


router.get('/banners/*', function (req, res) {
  res.sendFile( path.join(__dirname, '../img/'+ req.url) )
})

router.post('/create',(req,res,next)=>{
  const {url} = req.body

  BannerSchema.find().then(result=>{
      const banner = new BannerSchema({
        img_id:result.length?result[result.length-1].img_id+1:0,
        url
      })
      console.log(banner)
      banner.save().then(result => {
          res.json({
              code:200,
              data:result,
              message:'创建完成',
          })
      })
  })
})

router.get('/find',(req,res,next)=>{
  BannerSchema
    .find()
    .then(result => {
      if(result){
          res.json({
          code:200,
          data:result,
          message:'查询成功',
        })
      }
      else{
          res.json({
              code:400,
              message:'查询失败',
          })
      }
    })
})

module.exports = router